#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
连接诊断脚本
"""

import requests
import json
import time

def diagnose_connection():
    """诊断连接问题"""
    base_url = "http://localhost:5000"
    
    print("🔍 开始诊断实时检测连接问题...")
    print("=" * 50)
    
    # 1. 测试服务器是否运行
    print("\n1. 测试服务器连接...")
    try:
        response = requests.get(f"{base_url}/", timeout=5)
        if response.status_code == 200:
            print("✅ 服务器运行正常")
            data = response.json()
            print(f"   服务器信息: {data.get('message', 'unknown')}")
        else:
            print(f"❌ 服务器响应异常: {response.status_code}")
            return False
    except requests.exceptions.ConnectionError:
        print("❌ 无法连接到服务器")
        print("   请确保服务器正在运行: python realtime_pose_server.py")
        return False
    except Exception as e:
        print(f"❌ 连接错误: {e}")
        return False
    
    # 2. 测试状态接口
    print("\n2. 测试状态接口...")
    try:
        response = requests.get(f"{base_url}/api/pose/status", timeout=5)
        if response.status_code == 200:
            print("✅ 状态接口正常")
            data = response.json()
            print(f"   状态: {data.get('status', 'unknown')}")
        else:
            print(f"❌ 状态接口异常: {response.status_code}")
    except Exception as e:
        print(f"❌ 状态接口错误: {e}")
    
    # 3. 测试实时处理接口
    print("\n3. 测试实时处理接口...")
    try:
        response = requests.post(f"{base_url}/api/pose/realtime/start", timeout=5)
        if response.status_code == 200:
            print("✅ 开始处理接口正常")
            data = response.json()
            print(f"   响应: {data.get('message', 'unknown')}")
        else:
            print(f"❌ 开始处理接口异常: {response.status_code}")
    except Exception as e:
        print(f"❌ 开始处理接口错误: {e}")
    
    # 4. 测试SSE流接口
    print("\n4. 测试SSE流接口...")
    try:
        response = requests.get(f"{base_url}/api/pose/realtime/stream", 
                              headers={'Accept': 'text/event-stream'}, 
                              timeout=10, 
                              stream=True)
        if response.status_code == 200:
            print("✅ SSE流接口正常")
            print("   开始接收流数据...")
            
            # 尝试读取前几行数据
            count = 0
            for line in response.iter_lines():
                if line:
                    print(f"   收到数据: {line.decode('utf-8')[:100]}...")
                    count += 1
                    if count >= 3:  # 只读取前3行
                        break
        else:
            print(f"❌ SSE流接口异常: {response.status_code}")
    except Exception as e:
        print(f"❌ SSE流接口错误: {e}")
    
    # 5. 测试停止接口
    print("\n5. 测试停止接口...")
    try:
        response = requests.post(f"{base_url}/api/pose/realtime/stop", timeout=5)
        if response.status_code == 200:
            print("✅ 停止处理接口正常")
            data = response.json()
            print(f"   响应: {data.get('message', 'unknown')}")
        else:
            print(f"❌ 停止处理接口异常: {response.status_code}")
    except Exception as e:
        print(f"❌ 停止处理接口错误: {e}")
    
    print("\n" + "=" * 50)
    print("🎯 诊断建议:")
    print("1. 如果服务器无法连接，请运行: python realtime_pose_server.py")
    print("2. 如果SSE流有问题，请检查浏览器控制台")
    print("3. 如果CORS错误，请检查服务器CORS配置")
    print("4. 使用 test_connection.html 进行详细测试")
    
    return True

if __name__ == "__main__":
    diagnose_connection()



